package com.easyadmin.service.impl;

import com.easyadmin.entity.enums.PageSize;
import com.easyadmin.entity.po.SysOperationLog;
import com.easyadmin.entity.query.SysOperationLogQuery;
import com.easyadmin.entity.vo.PaginationResult;
import com.easyadmin.entity.vo.SimplePage;
import com.easyadmin.exception.BusinessException;
import com.easyadmin.mappers.SysOperationLogMapper;
import com.easyadmin.service.SysOperationLogService;
import com.easyadmin.utils.JsonUtils;
import com.easyadmin.utils.OKHttpUtils;
import com.easyadmin.utils.StringTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


/**
 * 操作日志 业务接口实现
 */
@Service("sysOperationLogService")
public class SysOperationLogServiceImpl implements SysOperationLogService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SysOperationLogMapper<SysOperationLog, SysOperationLogQuery> sysOperationLogMapper;

    /**
     * 根据条件查询列表
     */
    @Override
    public List<SysOperationLog> findListByParam(SysOperationLogQuery param) {
        return this.sysOperationLogMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(SysOperationLogQuery param) {
        return this.sysOperationLogMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResult<SysOperationLog> findListByPage(SysOperationLogQuery param) {
        int count = this.sysOperationLogMapper.selectCount(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();
        int pageNo = 0;
        if (null != param.getPageNo()) {
            pageNo = param.getPageNo();
        }
        SimplePage page = new SimplePage(pageNo, count, pageSize);
        param.setSimplePage(page);
        List<SysOperationLog> list = this.sysOperationLogMapper.selectList(param);
        PaginationResult<SysOperationLog> result = new PaginationResult<>(count, pageSize, pageNo, page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(SysOperationLog bean) throws BusinessException {
        try {
            return this.sysOperationLogMapper.insert(bean);
        } catch (DuplicateKeyException e) {
            throw new BusinessException("信息已经存在");
        }
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<SysOperationLog> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.sysOperationLogMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<SysOperationLog> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.sysOperationLogMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 根据Id修改
     */
    @Override
    public Integer updateById(SysOperationLog bean, Integer id) {
        return this.sysOperationLogMapper.updateById(bean, id);
    }


    /**
     * 根据Id删除
     */
    @Override
    public Integer deleteById(Integer id) {
        return this.sysOperationLogMapper.deleteById(id);
    }


    /**
     * 根据Id获取对象
     */
    @Override
    public SysOperationLog getSysOperationLogById(Integer id) {
        return this.sysOperationLogMapper.selectById(id);
    }

    @Override
    @Async
    public void saveSysOperationLog(SysOperationLog log) {
        final String ipUrl = "http://whois.pconline.com.cn/ipJson.jsp?ip=%s";
        String ip = log.getIp();
        if (!StringTools.isEmpty(ip)) {
            try {
                String response = OKHttpUtils.getRequest(String.format(ipUrl, ip), null);
                if (!StringTools.isEmpty(response)) {
                    response = response.replace("if(window.IPCallBack) {IPCallBack(", "");
                    response = response.replace(");}", "");
                    Map<String, String> responseObj = JsonUtils.convertJson2Obj(response, Map.class);
                    String address = responseObj.get("addr");
                    log.setIpAddress(address);
                }
            } catch (Exception e) {
                logger.error("获取IP地址失败,IP:{}", ip, e);
            }

        }
        this.sysOperationLogMapper.insert(log);
    }
}